import { useMemo } from "react"
import { useProject } from "utils/project"
import { useSetSearchUrlParams, useUrlQueryParam } from "utils/url"

export const useProjectsSearchParams = () => {
  const [param, setParam] = useUrlQueryParam(['name', 'personId'])
  return [
    useMemo(() => ({...param, personId: Number(param.personId) || undefined}), [param]),
    setParam
  ] as const
}

export const useProjectsQueryKey = () => {
  const [params] = useProjectsSearchParams()
  return ['projects', params]
}

export const useProjectModal = () => {
  const [{projectCreate}, setProjectCreate] = useUrlQueryParam(['projectCreate'])
  const [{editingProjectId}, setEditingProjectId] = useUrlQueryParam(['editingProjectId'])
  const setUrlParams = useSetSearchUrlParams()
  const {data: editingProject, isLoading} = useProject(Number(editingProjectId))

  const open = () => setProjectCreate({projectCreate: true})
  const close = () => {
    setUrlParams({projectCreate: "", editingProjectId: ""})
    // console.log('exec close function')
    // if (projectCreate) {
    //   setProjectCreate({projectCreate: undefined})
    // } else {
    //   setEditingProjectId({editingProjectId: undefined})
    // }
  }
  const startEdit = (id: number) => setEditingProjectId({editingProjectId: id})

  return {
    projectModelOpen: projectCreate === 'true' || Boolean(editingProjectId),
    open,
    close,
    startEdit,
    editingProject,
    isLoading,
  }
}